package com.siyao.redvip.ui.activity;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.json.JSONException;
import org.json.JSONObject;
import android.content.Context;
import android.content.Intent;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.provider.Settings;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.http.RequestManager;
import com.android.volley.http.RequestManager.RequestListener;
import com.android.volley.http.RequestMap;
import com.siyao.redvip.R;
import com.siyao.redvip.RedApplication;
import com.siyao.redvip.components.base.BaseImageChooseActivity;
import com.siyao.redvip.network.NetConstans;
import com.siyao.redvip.ui.adapter.ImagePickerAdapter.ChooseImageAdapterCallBack;
import com.siyao.redvip.utils.AppUtils;
import com.siyao.redvip.utils.ToastUtils;
import com.siyao.redvip.utils.Track;

/**
 * 拍照上传信息
 * 
 * @author lenovo
 * 
 */
public class PhotoActivity extends BaseImageChooseActivity implements
		ChooseImageAdapterCallBack {

	private TextView textGps;
	private Button btnSendPhoto;
	private String location = "";// 位置信息
	private LocationManager locMan;
	private Location loc;
	private Geocoder g;
	private String hdxxId="";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
	}

	@Override
	protected void beforeInit() {
		try {
			hdxxId=getIntent().getStringExtra("hdxxId");
			locMan = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
			loc = locMan.getLastKnownLocation(LocationManager.GPS_PROVIDER);
			//判断GPS是否正常启动
	        if(!locMan.isProviderEnabled(LocationManager.GPS_PROVIDER)){
	            Toast.makeText(this, "请开启GPS导航...", Toast.LENGTH_SHORT).show();
	            //返回开启GPS导航设置界面
	            Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);   
	            startActivityForResult(intent,0); 
	            return;
	        }
	        
			if (loc == null) {
				loc = locMan.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
			} 
			
			if(loc!=null){
				double lat = loc.getLatitude();
				Track.i("latitude: " + lat);
				double lng = loc.getLongitude();
				Track.i("longitude: " + lng);
				String url = NetConstans.MAPURL + "?latlng=" + lat + "," + lng
						+ "&sensor=true&language=zh-CN";
				g = new Geocoder(this);
				List<Address> list = g.getFromLocation(lat, lng, 1);
				if (!list.isEmpty()) {
					Address addr = list.get(0);
					location += addr.getAddressLine(0);
				}
				Track.i(list.size() + "");
			}else{
				ToastUtils.makeMesageShort(this, "请打开GPS定位,否则不能定位到你的地理信息");
			}
		} catch (IOException e) {
		}
	}
	
	private void openGPSSettings() {
        LocationManager alm = (LocationManager) this
                .getSystemService(Context.LOCATION_SERVICE);
        if (alm.isProviderEnabled(android.location.LocationManager.GPS_PROVIDER)) {
            Toast.makeText(this, "GPS模块正常", Toast.LENGTH_SHORT).show();
            return;
        }

        Toast.makeText(this, "请开启GPS！", Toast.LENGTH_SHORT).show();
        Intent intent = new Intent(Settings.ACTION_SECURITY_SETTINGS);
        startActivityForResult(intent,0); //此为设置完成后返回到获取界面

    }

	@Override
	protected void setContentView() {
		setTitleText("发布动态");
		setTitleLeftButton("取消");
		View appView = getLayoutInflater().inflate(
				R.layout.activity_photo_fragment, null);
		appMainView.addView(appView, layoutParams);
	}

	@Override
	protected void initComponent() {
		textGps = (TextView) findViewById(R.id.text_gps);
		btnSendPhoto = (Button) findViewById(R.id.btn_send_photo);
		btnSendPhoto.setOnClickListener(this);
		textGps.setText(location);
	}

	@Override
	protected void initData() {

	}

	@Override
	public void onClick(View v) {
		super.onClick(v);
		int id =v.getId();
		switch (id) {
		case R.id.btn_send_photo:
			publishDynamic();
			break;
			
		case R.id.top_left_btn:
			Intent intent = new Intent(this, RedvipMainActivity.class);
			startActivity(intent);
			break;
		default:
			break;
		}
	}

	private void publishDynamic() {
		showPd();
		if(!photos.isEmpty()){
					RequestMap params = new RequestMap();
					params.put("activityId", hdxxId);
					params.put("memberNo", RedApplication.getInstance().getUser().getVolunteerId()+"");
					params.put("location", location);
					List<File> files = new ArrayList<File>();
					for (int i = 0; i < photos.size(); i++) {
						String loadImgTemp = AppUtils.removeFileHeader(photos.get(i));
						 File file= AppUtils.copeFile(new File(loadImgTemp));
						params.put("file"+i, file);
					}
					String url=NetConstans.PUBLISH_PHOTO;
					RequestManager.getInstance(PhotoActivity.this).post(url, params, new RequestListener() {
						@Override
						public void onSuccess(String response, String url, int actionId) {
							Track.i("返回数据：--->"+response);
							try {
								JSONObject json = new JSONObject(response);
								int status =json.getInt("status");
								if(status==1){
									dismissPd();
									ToastUtils.makeMesageShort(PhotoActivity.this, "上传成功！");
									Intent intent = new Intent(PhotoActivity.this, FriendActivity.class);
									startActivity(intent);
									finish();
								}else{
									String message = json.getString("message");
									ToastUtils.makeMesageShort(PhotoActivity.this,message);
									dismissPd();
								}
							} catch (JSONException e) {
							}
						}
						@Override
						public void onRequest() {
						}
						@Override
						public void onError(String errorMsg, String url, int actionId) {
							dismissPd();
							ToastUtils.makeMesageShort(PhotoActivity.this,getString(R.string.server_error));
						}
					}, 2);
		}else{
			dismissPd();
			ToastUtils.makeMesageLong(this, "请先选择照片");
		}
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
	}
}
